<template>
<div style="padding: 56px 0 18px;">
	<div class="edit-head">
		<img @click="backHome" style="width: 20px;padding: 18px 18px 18px 14px;" src="static/ic_back.png">
		<span class="edit-head-text">{{name}}</span>
	</div>
  <div style="padding:0 24px;background: #fff;">
  <div class="options">
    <div @click="changeCurr(0)" :class="current===0&&'checked'">日</div>
    <div @click="changeCurr(1)" :class="current===1&&'checked'">周</div>
    <div @click="changeCurr(2)" :class="current===2&&'checked'">月</div>
    <div @click="changeCurr(3)" :class="current===3&&'checked'">年</div>
  </div>
  <div style="margin-top: 10px;" class="between">
    <img @click="goto(-1)" class="arrow" style="transform: rotate(180deg);" src="static/center/right_grey.png">
    <div style="opacity: .9;">{{today}}</div>
    <img @click="goto(1)" :style="!isShowAfter&&'opacity: 0'" class="arrow" src="static/center/right_grey.png">
  </div>
  <div style="margin-top: 12px;text-align: center;color: rgba(0,0,0,0.60);line-height: 16px;">{{xValue}}</div>
  <div style="margin-top: 10px;margin-bottom: 6px;text-align: center;color: rgba(0,0,0,0.60);">
     <span style="font-size: 20px;line-height: 26px;font-weight: 500;color: #000000;">{{yValue}}</span> {{type}}
  </div>
  <div ref="chart"></div>
  </div>
  <div style="padding: 0 12px">
    <div class="bold" style="margin: 24px 8px 8px;">定时</div>
    <div class="box">
      <div style="color: rgba(0,0,0,0.60);font-weight: 500;margin-bottom: 4px;">{{recurrence}}</div>
      <template :key="item.time" v-for="item in schedules">
      <div class="between item">
        <div class="bold">{{item.time}}</div>
        <div style="opacity: 0.6;">{{item.objectiveInfos[0].metricValue}} {{type}}</div>
      </div>
      <div class="line"></div>
      </template>
      <div @click="edit" class="bold" style="color: #00A5AD;line-height:48px;">编辑</div>
    </div>
    <div @click="gotoList" style="border-radius: 8px;background: #FFFFFF;height:40px;display: flex;
    align-items: center;justify-content: center;margin-top: 12px;"><img style="width:24px;margin-right:6px;" src="@/assets/medicine/显示所有数据.png" alt="">显示所有数据</div>
  </div>
  <!-- <pre @click="$root.reload" style="background:yellow;min-height: 100px;">{{wdata}}</pre> -->
</div>
</template>

<script>
	export default {
		data() {
			return {
        current:0,
        currentTime:0,
        isShowAfter:false,
        wdata:'',
        today:'',
        schedules:[],
        name:'',
        type:'',
        recurrence:'',
        day:0,
        xValue:'--',
        yValue:'--',
        option:{
          grid: {
            // height: '80%',
            // top: '5%',
            // left: '6%',
            // right: '6%',
            top: '8',
            left: '0',
            right: '0',
            bottom: '34',
            containLabel: true,
          },
          xAxis: {
            axisPointer: {
              value: '',
              snap: true,
              lineStyle: {
                color: '#5EA1FF',
                width: 0.6
              },
              label: {
                show: false,
              },
              handle: {
                show: true,
                size: 24,
                margin: 35,
                color: '#fff',
                //滑块的圆
                // icon:'path("M -126.007 267.628 v -12 c -19.389 0 -33.466 -10.595 -33.466 -10.595 l -0.004 0.006 c -2.59 -2.13 -5.907 -3.411 -9.523 -3.411 c -3.765 0 -7.196 1.396 -9.83 3.687 c -2.106 1.54 -15.411 10.313 -33.176 10.313 v 12 H -126.007 Z")'
                icon: 'path("M 300,300 A 100,100 0 1 1 300,299 Z")',
                shadowColor: 'rgba(0, 0, 0, 0.2)',
                shadowBlur: 4,
                // shadowOffsetY:10, //阴影垂直方向上的偏移距离。
              },
            },
            axisTick: {
              inside: true,
              boundaryGap: false,
              show: false,
            },
            // 现在坐标系刻度最大值、最小值
            axisLabel: {
              interval: 0,
              //x轴文字颜色
              color: 'rgba(0,0,0,.4)'
            },
            axisLine: {
              //x线
              lineStyle: {
                color: '#DEDEDE',
                // color: 'rgba(0,0,0,.2)',
              },
            },
            data: ["00:00", {
              value:"06:00",
              // textStyle:{
              //   color:'red',
              //   padding: [6, 0, 0, 0]
              // }
            },  "12:00",  "18:00", "00:00"
            ],
          },
          yAxis: {
            type: 'value',
            position: 'right',
            // boundaryGap: [0, '15%'],
            splitNumber: 4,
            min: 0,
            nameTextStyle: {
              align: 'center',
            },
            axisLabel: {
              color: 'rgba(0,0,0,.4)',
            },
            //去掉Y轴坐标线
            axisLine: {
              show: false,
            },
            //刻度线显示
            axisTick: {
              show: false,
            },
            splitLine: {
              //网格线
              lineStyle: {
                type: 'solid', //设置网格线类型 dotted：虚线 solid:实线
                color: '#F1F3F5',
              },
              show: true,
            },
          },
          series: [{
            type: 'bar',
            barWidth: '8',
            data: [2,3,4],
            itemStyle: {
              color: 'rgb(38, 129, 255,.6)', //为未选中颜色
              borderRadius: [18, 18, 0, 0],
            },
            emphasis: {
              itemStyle: {
                color: '#2681FF', //为选中颜色
              }
            },
          }],
        },
        myChart:null
			}
		},
		mounted() {
      this.$root.medicineForm={"desc":"Capsule","time":"07:00/12:30/18:00",isCalen:false}
      var query=this.$route.query
      this.name=query.name
      this.type=query.unit+query.type
      this.recurrence=query.recurrence
      window.tmp=this
      this.$refs.chart.style.height=(window.innerWidth-48)*0.55+'px'
      this.myChart = echarts.init(this.$refs.chart)
      this.currentTime=Date.now()
      var taskId=query.id
      this.schedules=JSON.parse(research_obj.querySchedules(JSON.stringify({
        taskId
      }))||'[]')
      var option=this.option
      var myChart=this.myChart
      this.myChart.getZr().on('mousemove',params=>{
        var list=[params.offsetX,params.offsetY]
        var point=myChart.convertFromPixel({seriesIndex:0},list)
        console.log(point[0])
        var xValue=option.xAxis.data[point[0]]
        if(this.current===3){
          this.xValue=xValue?xValue+'月':'--'
        }else{
          this.xValue=xValue||'--'
        }
        var yValue=option.series[0].data[point[0]]
        this.yValue=yValue||'--'
        myChart.dispatchAction({
          type:'downplay',
          seriesIndex:0
        })
        myChart.dispatchAction({
          type:'highlight',
          seriesIndex:0,
          dataIndex:point[0]
        })
        // if(this.myChart)
        // console.log(params)
        // var handler = this.myChart.getZr().handler
        // console.log(handler)
        // handler.dispatch("click", {
        //   zrX: params.offsetX,
        //   zrY: params.offsetY
        // });
        // this.wdata=params||'xxx'
      })
      // this.myChart.on('highlight', function(params) {
      //   console.log(11111111)
        // let dataIndex = params.batch[0].dataIndex
        // setTimeout(() => {
        // 	that.setValueTxt(dataIndex)
        // }, 10)
      // });
      // this.myChart.setOption(this.option)
			this.init()
		},
		methods: {
      touchMove(e){
        console.log(e)
        var touch = e.touches[0]
        var handler = this.myChart.getZr().handler
        handler.dispatch("mousemove", {
          zrX: touch.x,
          zrY: touch.y
        })
      },
      edit(){
        this.$root.isModifyMedicine=true
        this.$router.push('/medicine/add?id='+this.$route.query.id)
      },
      changeCurr(i){
        if(this.current===i)return
        this.current=i
        if(i===0){
          this.init()
          return
        }
        if(i===1){
          this.init1()
          return
        }
        if(i===2){
          this.init2()
          return
        }
        this.init3()
      },
      gotoList(){
        var query=this.$route.query
        this.$router.push('/medicine/list?id='+query.id+'&name='+query.name+'&unit='+query.unit)
      },
      init(){
        this.today=this.getToday(this.currentTime)
        var resultss=[]
        var xDate=['00:00']
        var yDate=[0]
        var today=this.getDate1(this.currentTime)
        this.isShowAfter=today<this.getDate1(Date.now())
        for(var j of this.schedules){
          var HOUR=j.recurrence.indexOf('HOUR')
          var MINU=j.recurrence.indexOf('MINU')
          j.time=j.recurrence.slice(HOUR+5,HOUR+7)+':'+j.recurrence.slice(MINU+7,MINU+9)
          xDate.push(j.time)
          var results=JSON.parse(research_obj.queryScheduleResults(JSON.stringify({
            taskId:j.taskId,
            scheduleId:j.scheduleId,
            startDay:today,
            endDay:today
          }))||'[]')
          if(results.length){
            yDate.push(results[0].objectiveInfos[0].metricValue)
          }
          resultss=resultss.concat(results)
        }
        xDate.push('00:00')
        this.xValue=xDate[xDate.length-1]
        this.yValue=yDate[xDate.length-1]||'--'
        this.option.xAxis.data=xDate
        this.option.series[0].data=yDate
        this.wdata=resultss
        this.myChart.setOption(this.option)  
      },
      init1(){
        var resultss=[]
        var yDate=[0,0,0,0,0,0,0]
        var endDay
        var startDay
        if(this.day===0){
          endDay=this.getDate1(this.currentTime)
          this.today=`${this.getDate(this.currentTime-86400000*6)} - ${this.getDate(this.currentTime)}`
          startDay=this.getDate1(this.currentTime-86400000*6)
        }else{
          endDay=this.getDate1(this.currentTime+86400000*(7-this.day))
          this.today=`${this.getDate(this.currentTime-86400000*(this.day-1))} - ${this.getDate(this.currentTime+86400000*(7-this.day))}`
          startDay=this.getDate1(this.currentTime-86400000*(this.day-1))
        }
        this.isShowAfter=endDay<this.getDate1(Date.now())
        for(var j of this.schedules){
          var results=JSON.parse(research_obj.queryScheduleResults(JSON.stringify({
            taskId:j.taskId,
            scheduleId:j.scheduleId,
            startDay:startDay,
            endDay:endDay
          }))||'[]')
          resultss=resultss.concat(results)
        }
        for(var i of resultss){
          if(new Date(i.endTime).getDay()===0){
            yDate[6]+=+i.objectiveInfos[0].metricValue
          }else{
            yDate[new Date(i.endTime).getDay()-1]+=+i.objectiveInfos[0].metricValue
          }
        }
        this.wdata=resultss
        this.option.xAxis.data=['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        this.option.series[0].data=yDate
        this.xValue='周日'
        this.yValue=yDate[6]||'--'
        this.myChart.setOption(this.option)  
      },
      init2(){
        var date=new Date(this.currentTime)
        var month=date.getMonth()
        var day = date.getDate()
        this.today=`${month + 1}月`
        var resultss=[]
        var monthNum=[31,28,31,30,31,30,31,31,30,31,30,31][month]
        var xDate=[(month+1)+'/01']
        var yDate=[0]
        var endDay=this.getDate1(this.currentTime+86400000*(monthNum-day))
        var startDay=this.getDate1(this.currentTime-86400000*(day-1))
        this.isShowAfter=endDay<this.getDate1(Date.now())
        for(var j of this.schedules){
          var results=JSON.parse(research_obj.queryScheduleResults(JSON.stringify({
            taskId:j.taskId,
            scheduleId:j.scheduleId,
            startDay:startDay,
            endDay:endDay
          }))||'[]')
          resultss=resultss.concat(results)
        }
        for(var i of resultss){
          var str=(month+1)+'/'+new Date(i.endTime).getDate()
          var index=xDate.indexOf(str)
          if(index!==-1){
            yDate[index]+=+i.objectiveInfos[0].metricValue
          }else{
            xDate.push(str)
            yDate.push(+i.objectiveInfos[0].metricValue)
          }
        }
        if(xDate[xDate.length-1]!==(month+1)+'/'+monthNum){
          xDate.push((month+1)+'/'+monthNum)
        }
        this.wdata=resultss
        this.option.xAxis.data=xDate
        this.option.series[0].data=yDate
        this.xValue=xDate[xDate.length-1]
        this.yValue=yDate[xDate.length-1]||'--'
        this.myChart.setOption(this.option)  
      },
      init3(){
        var date=new Date(this.currentTime)
        var year=date.getFullYear()
        this.today=`${year}年`
        var resultss=[]
        var xDate=[1,2,3,4,5,6,7,8,9,10,11,12]
        var yDate=[]
        var endDay=this.getDate1(year+'-12-31')
        var startDay=this.getDate1(year+'-01-01')
        this.isShowAfter=endDay<this.getDate1(Date.now())
        for(var j of this.schedules){
          var results=JSON.parse(research_obj.queryScheduleResults(JSON.stringify({
            taskId:j.taskId,
            scheduleId:j.scheduleId,
            startDay:startDay,
            endDay:endDay
          }))||'[]')
          resultss=resultss.concat(results)
        }
        for(var i of resultss){
          var index=new Date(i.endTime).getMonth()
          if(yDate[index]){
            yDate[index]+=+i.objectiveInfos[0].metricValue
          }else{
            yDate[index]=+i.objectiveInfos[0].metricValue
          }
        }
        this.wdata=resultss
        this.option.xAxis.data=xDate
        this.option.series[0].data=yDate
        this.xValue=xDate[xDate.length-1]+'月'
        this.yValue=yDate[xDate.length-1]||'--'
        this.myChart.setOption(this.option)  
      },
      goto(index){
        var monthNum=[31,28,31,30,31,30,31,31,30,31,30,31][new Date(this.currentTime).getMonth()]
        var list=[1,7,monthNum,365]
        this.currentTime=this.currentTime+86400000*index*list[this.current]
        var curr=this.current
        if(curr===0){
          this.init()
          return
        }
        if(curr===1){
          this.init1()
          return
        }
        if(curr===2){
          this.init2()
          return
        }
        this.init3()
      },
      getToday(date){
        var date=new Date(date)
        var month = date.getMonth() + 1
        var day = date.getDate()
        var d = date.getDay()
        this.day=d
        var list = ['日','一','二','三','四','五','六']
        return `${month}月${day}日 星期${list[d]}`
      },
			backHome(){
				history.back()
			},
			getDate(date){
				date=new Date(date)
				var month = date.getMonth() + 1
				var day = date.getDate()
				return `${month}月${day}日`
			},
      getDate1(date){
        var date=new Date(date)
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var day = date.getDate()
        month < 10 && (month = "0" + month)
        day < 10 && (day = "0" + day)
        return `${year}${month}${day}`
      },
			getTime(date){
				if(!date){
					return '--'
				}
				var m=Math.floor(date/60)
				var s=date%60
				if(m>0){
					return `${m} 分 ${s} 秒`
				}
				return `${s} 秒`
			}
		}
	}
</script>

<style scoped>
.checked{
  color: #00A5AD;
  border-bottom: 2px solid #00A5AD;
}
.arrow{
	width: 12px;
  opacity: .2;
	margin-left: 4px;
}
.options{
  display: flex;
  justify-content: space-around;
  text-align: center;
  padding: 0 36px;
  font-size: 16px;
}
.options>div{
  width: 32px;
  line-height: 34px;
}
.item-title{
	font-size: 16px;
}
.item{
	height: 48px;
}
.item-unit{
	font-size: 16px;
}
.box{
	background: #fff;
	padding: 12px 12px 4px;
	border-radius: 16px;
}
.edit-head-text{
	font-size: 20px;
    font-weight: 500;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: calc(100vw - 140px);
}
.edit-head{
	position: fixed;
    width: 100%;
    top: 0;
    left: 0;
    padding: 0 12px;
	box-sizing: border-box;
	z-index: 9;
    background: #fff;
	display:flex;
	align-items: center;
}
.line{
	height: 1px;
	background: rgba(0,0,0,.05);
}
.between{
	display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>
